package demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class PlaneGame extends JFrame {
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;
    private static final int PLAYER_SIZE = 50;
    private static final int ENEMY_SIZE = 40;
    private static final int BULLET_SIZE = 10;
    private static final int PLAYER_SPEED = 8;
    private static final int ENEMY_SPEED = 3;
    private static final int BULLET_SPEED = 10;

    private int playerX = WIDTH / 2 - PLAYER_SIZE / 2;
    private int playerY = HEIGHT - 100;
    private boolean leftPressed = false;
    private boolean rightPressed = false;
    private boolean upPressed = false;
    private boolean downPressed = false;
    private boolean gameOver = false;
    private int score = 0;

    private ArrayList<Point> bullets = new ArrayList<>();
    private ArrayList<Point> enemies = new ArrayList<>();
    private Random random = new Random();
    private GamePanel gamePanel;

    public PlaneGame() {
        setTitle("Java打飞机小游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        // 使用GamePanel作为画布
        gamePanel = new GamePanel();
        add(gamePanel);

        // 方案1：直接设置窗口大小（简单）r
        // setSize(WIDTH, HEIGHT);

        // 方案2：精确控制内容区域大小（推荐）
        getContentPane().setPreferredSize(new Dimension(WIDTH, HEIGHT));
        pack();

        setLocationRelativeTo(null);

        // 添加键盘监听
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                handleKeyPress(e);
            }

            @Override
            public void keyReleased(KeyEvent e) {
                handleKeyRelease(e);
            }
        });

        // 游戏主循环
        Timer gameTimer = new Timer(30, e -> {
            if (!gameOver) {
                updateGame();
                gamePanel.repaint();
            }
        });
        gameTimer.start();

        // 敌人生成器
        Timer enemyTimer = new Timer(1000, e -> {
            if (!gameOver) {
                spawnEnemy();
            }
        });
        enemyTimer.start();
    }

    private class GamePanel extends JPanel {
        public GamePanel() {
            setPreferredSize(new Dimension(WIDTH, HEIGHT));
            setBackground(Color.BLACK);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 绘制玩家飞机
            g.setColor(Color.GREEN);
            g.fillRect(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE);

            // 绘制子弹
            g.setColor(Color.YELLOW);
            for (Point bullet : bullets) {
                g.fillOval(bullet.x, bullet.y, BULLET_SIZE, BULLET_SIZE);
            }

            // 绘制敌人
            g.setColor(Color.RED);
            for (Point enemy : enemies) {
                g.fillRect(enemy.x, enemy.y, ENEMY_SIZE, ENEMY_SIZE);
            }

            // 绘制分数
            g.setColor(Color.WHITE);
            g.setFont(new Font("Arial", Font.BOLD, 20));
            g.drawString("分数: " + score, 20, 30);

            // 游戏结束画面
            if (gameOver) {
                g.setColor(new Color(255, 0, 0, 150));
                g.fillRect(0, 0, WIDTH, HEIGHT);

                g.setColor(Color.WHITE);
                g.setFont(new Font("Arial", Font.BOLD, 50));
                String gameOverText = "游戏结束! 最终分数: " + score;
                int textWidth = g.getFontMetrics().stringWidth(gameOverText);
                g.drawString(gameOverText, WIDTH / 2 - textWidth / 2, HEIGHT / 2 - 50);

                g.setFont(new Font("Arial", Font.PLAIN, 20));
                String restartText = "按R键重新开始";
                textWidth = g.getFontMetrics().stringWidth(restartText);
                g.drawString(restartText, WIDTH / 2 - textWidth / 2, HEIGHT / 2 + 20);
            }
        }
    }

    private void handleKeyPress(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                leftPressed = true;
                break;
            case KeyEvent.VK_RIGHT:
                rightPressed = true;
                break;
            case KeyEvent.VK_UP:
                upPressed = true;
                break;
            case KeyEvent.VK_DOWN:
                downPressed = true;
                break;
            case KeyEvent.VK_SPACE:
                fireBullet();
                break;
            case KeyEvent.VK_R:
                if (gameOver) resetGame();
                break;
        }
    }

    private void handleKeyRelease(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                leftPressed = false;
                break;
            case KeyEvent.VK_RIGHT:
                rightPressed = false;
                break;
            case KeyEvent.VK_UP:
                upPressed = false;
                break;
            case KeyEvent.VK_DOWN:
                downPressed = false;
                break;
        }
    }

    private void updateGame() {
        // 更新玩家位置
        if (leftPressed) playerX = Math.max(0, playerX - PLAYER_SPEED);
        if (rightPressed) playerX = Math.min(WIDTH - PLAYER_SIZE, playerX + PLAYER_SPEED);
        if (upPressed) playerY = Math.max(0, playerY - PLAYER_SPEED);
        if (downPressed) playerY = Math.min(HEIGHT - PLAYER_SIZE, playerY + PLAYER_SPEED);

        // 更新子弹位置
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Point bullet = bullets.get(i);
            bullet.y -= BULLET_SPEED;
            if (bullet.y < 0) {
                bullets.remove(i);
            }
        }

        // 更新敌人位置
        for (int i = enemies.size() - 1; i >= 0; i--) {
            Point enemy = enemies.get(i);
            enemy.y += ENEMY_SPEED;
            if (enemy.y > HEIGHT) {
                enemies.remove(i);
            }
        }

        // 检测碰撞
        checkCollisions();
    }

    private void fireBullet() {
        bullets.add(new Point(playerX + PLAYER_SIZE / 2 - BULLET_SIZE / 2, playerY));
    }

    private void spawnEnemy() {
        int x = random.nextInt(WIDTH - ENEMY_SIZE);
        enemies.add(new Point(x, -ENEMY_SIZE));
    }

    private void checkCollisions() {
        // 子弹与敌人碰撞
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Point bullet = bullets.get(i);
            Rectangle bulletRect = new Rectangle(bullet.x, bullet.y, BULLET_SIZE, BULLET_SIZE);

            for (int j = enemies.size() - 1; j >= 0; j--) {
                Point enemy = enemies.get(j);
                Rectangle enemyRect = new Rectangle(enemy.x, enemy.y, ENEMY_SIZE, ENEMY_SIZE);

                if (bulletRect.intersects(enemyRect)) {
                    bullets.remove(i);
                    enemies.remove(j);
                    score += 10;
                    break;
                }
            }
        }

        // 玩家与敌人碰撞
        Rectangle playerRect = new Rectangle(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE);
        for (Point enemy : enemies) {
            Rectangle enemyRect = new Rectangle(enemy.x, enemy.y, ENEMY_SIZE, ENEMY_SIZE);
            if (playerRect.intersects(enemyRect)) {
                gameOver = true;
                break;
            }
        }
    }

    private void resetGame() {
        playerX = WIDTH / 2 - PLAYER_SIZE / 2;
        playerY = HEIGHT - 100;
        bullets.clear();
        enemies.clear();
        score = 0;
        gameOver = false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            PlaneGame game = new PlaneGame();
            game.setVisible(true);
        });
    }
}